<template>
  <el-dialog :visible="visible" :title="formData.id ? '编辑部门' : '新增部门'" @close="$emit('update:visible', false)">
    <el-form ref="addForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>

      <el-form-item prop="code" label="部门编码">
        <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>

      <el-form-item prop="managerId" label="部门负责人">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
          <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>

      </el-form-item>

      <el-form-item prop="introduce" label="部门介绍">
        <el-input
          v-model="formData.introduce"
          placeholder="1-100个字符"
          type="textarea"
          size="mini"
          :rows="4"
          style="width: 80%"
        />
      </el-form-item>

      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
            <el-button size="mini" @click="$emit('update:visible', false)">取消</el-button>

          </el-col>

        </el-row>

      </el-form-item>

    </el-form>

  </el-dialog>
</template>

<script>
import { addDepartmentAPI, getDepartmentAPI, getDepartmentDetailAPI, getManagerListAPI, updateDepartmentAPI } from '@/api/department'

export default {
  name: 'AddDep',
  props: {
    visible: Boolean,
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      managerList: [],
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      },
      rules: {
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码长度为2-10个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            // 自定义校验规则
            validator: async(rule, value, callback) => {
              // 发请求 获取所有的部门数据
              let list = await getDepartmentAPI()
              // 如果是编辑时, 比较之前, 要先把自身这个部门, 从数据中剔除掉
              if (this.formData.id) {
                // 编辑 时 排除自身
                list = list.filter(v => v.id !== this.formData.id)
              }
              const codeList = list.map(v => v.code.toUpperCase())
              if (codeList.includes(value.toUpperCase())) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            }
          }

        ],
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称长度为2-10个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            // 自定义校验规则
            validator: async(rule, value, callback) => {
              // 发请求 获取所有的部门数据
              let list = await getDepartmentAPI()
              if (this.formData.id) {
                // 编辑 时 排除自身
                list = list.filter(v => v.id !== this.formData.id)
              }
              const nameList = list.map(v => v.name)
              if (nameList.includes(value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
              // 校验value是否存在数据中
            }
          }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '部门介绍长度为1-100个字符', trigger: 'blur' }
        ],
        managerId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    visible(newValue) {
      if (!newValue) {
        this.$refs.addForm.resetFields() // 移除校验和数据
        this.formData = {
          code: '',
          introduce: '',
          managerId: '',
          name: ''
        }
      }
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    async onSubmit() {
      await this.$refs.addForm.validate()

      !this.formData.id
        ? await addDepartmentAPI({ ...this.formData, pid: this.currentId })
        : await updateDepartmentAPI(this.formData)

      this.$message.success(this.formData.id ? '编辑成功' : '新增成功')
      this.$emit('update:visible', false)
      this.$emit('refresh')
    },
    async getManagerList() {
      const res = await getManagerListAPI()
      this.managerList = res
    },
    async getDepDetail(id) {
      const res = await getDepartmentDetailAPI(id)
      console.log('res  ----->  ', res)
      this.formData = res
    }
  }

}
</script>

<style lang="scss" scoped></style>
